package util.security;

import static java.lang.System.getProperty;
import static java.lang.String.format;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.security.KeyStore;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

import util.CmdStartupHelper;

/**
 * Class used to add the server's certificate to the KeyStore with your trusted certificates.
 * 
 * @see http://blogs.sun.com/andreas/resource/InstallCert.java
 */
public class InstallCert {
	
	public static void main(final String[] args) throws Exception {
		final CmdStartupHelper sh = new CmdStartupHelper();
		sh.option("keystore", "path to keystore, default: ${java.home}/lib/security/cacerts");
		sh.option("pass", "keystore password, default: changeit");
		sh.target("host to fetch certificate from <host>[:port], default port: 443");
		sh.processArgs(args);
		
		String keystore = sh.getOption("keystore");
		if (keystore == null)
			keystore = getProperty("java.home") + "/lib/security/cacerts";
		String pass = sh.getOption("pass");
		if (pass == null)
			pass = "changeit";
		String host = sh.getTarget(0);
		int port = 443;
		if (host.contains(":")) {
			port = Integer.parseInt(host.substring(host.indexOf(":") + 1));
			host = host.substring(0, host.indexOf(":"));
		}
		
		final File file = new File(keystore);
		System.out.println("Loading KeyStore " + file.getAbsolutePath());
		final InputStream in = new FileInputStream(file);
		final KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
		ks.load(in, pass.toCharArray());
		in.close();
		
		final SSLContext context = SSLContext.getInstance("TLS");
		final TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
		tmf.init(ks);
		final X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0];
		final SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
		context.init(null, new TrustManager[] { tm }, null);
		final SSLSocketFactory factory = context.getSocketFactory();
		
		System.out.println("Opening connection to " + host + ":" + port);
		final SSLSocket socket = (SSLSocket) factory.createSocket(host, port);
		socket.setSoTimeout(10000);
		try {
			System.out.println("Starting SSL handshake");
			socket.startHandshake();
			socket.close();
			System.out.println("No errors, certificate is already trusted");
			return;
		} catch (final SSLException e) {
			System.out.println("SSL handshake failed. Certificate is not trusted");
		}
		
		final X509Certificate[] chain = tm.certificates;
		if (chain == null) {
			System.out.println("Could not obtain server certificate chain");
			return;
		}
		
		printCertificateChain(chain);
		
		final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
		System.out.println("Enter certificate to add to trusted keystore or 'q' to quit: [1]");
		
		final String line = reader.readLine().trim();
		int k;
		try {
			k = line.isEmpty()
					? 0
					: Integer.parseInt(line) - 1;
		} catch (final NumberFormatException e) {
			System.out.println("KeyStore not changed");
			return;
		}
		
		final X509Certificate cert = chain[k];
		final String alias = host + "-" + (k + 1);
		ks.setCertificateEntry(alias, cert);
		
		final OutputStream out = new FileOutputStream(file);
		ks.store(out, pass.toCharArray());
		out.close();
		
		System.out.println(cert);
		System.out.println("Added certificate to keystore 'jssecacerts' using alias '" + alias + "'");
	}
	
	private static final char[] HEXDIGITS = "0123456789abcdef".toCharArray();
	
	private static String toHexString(final byte[] bytes) {
		final StringBuilder sb = new StringBuilder(bytes.length * 3);
		for (int b : bytes) {
			b &= 0xff;
			sb.append(HEXDIGITS[b >> 4]);
			sb.append(HEXDIGITS[b & 15]);
			sb.append(' ');
		}
		return sb.toString();
	}
	
	private static class SavingTrustManager implements X509TrustManager {
		
		private final X509TrustManager tm;
		private X509Certificate[] certificates;
		
		SavingTrustManager(final X509TrustManager tm) {
			this.tm = tm;
		}
		
		@Override
		public X509Certificate[] getAcceptedIssuers() {
			throw new UnsupportedOperationException();
		}
		
		@Override
		public void checkClientTrusted(final X509Certificate[] chain, final String authType)
				throws CertificateException {
			throw new UnsupportedOperationException();
		}
		
		@Override
		public void checkServerTrusted(final X509Certificate[] chain, final String authType)
				throws CertificateException {
			certificates = chain;
			tm.checkServerTrusted(chain, authType);
		}
	}
	
	private static void printCertificateChain(X509Certificate[] chain) throws NoSuchAlgorithmException,
			CertificateEncodingException {
		System.out.println("Server sent " + chain.length + " certificate(s):");
		final MessageDigest sha1 = MessageDigest.getInstance("SHA1");
		final MessageDigest md5 = MessageDigest.getInstance("MD5");
		for (int i = 0; i < chain.length; i++) {
			final X509Certificate cert = chain[i];
			
			System.out.println(i + 1 + format("\t%-20s \t%s", "Subject", cert.getSubjectDN()));
			System.out.println(format("\t%-20s \t%s", "Issuer", cert.getIssuerDN()));
			sha1.update(cert.getEncoded());
			System.out.println(format("\t%-20s \t%s", "sha1", toHexString(sha1.digest())));
			md5.update(cert.getEncoded());
			System.out.println(format("\t%-20s \t%s", "md5", toHexString(md5.digest())));
		}
	}
}
